package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RegexUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;

import static com.hmdp.utils.SystemConstants.USER_NICK_NAME_PREFIX;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    // 定义常量
    public static final String SESSION_CODE_KEY = "code";
    public static final String SESSION_USER_KEY = "user";

    @Override
    public Result sendCode(String phone, HttpSession session) {
        // 验证手机号码格式
        if (RegexUtils.isPhoneInvalid(phone)){
            return Result.fail("您所提供的手机号格式有误");
        }
        //生成验证码
        String code = RandomUtil.randomNumbers(6);

        //保存验证码到session
        session.setAttribute("SESSION_CODE_KEY",code);

        //发送验证码
        log.debug("验证法发送成功：{}",code);
        return Result.ok();
    }

    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
//        验证手机号格式
        String phone = loginForm.getPhone();
        if (RegexUtils.isPhoneInvalid(phone)){
            return Result.fail("您所提供的手机号格式有误");
        }
//        校验验证码
        String code = loginForm.getCode();
        Object cachecode = session.getAttribute("SESSION_CODE_KEY");
        if (cachecode == null || code.equals(cachecode.toString()) == false) {
            return Result.fail("验证码错误");
        }

        // 根据手机号查询用户
        User user = query().eq("phone", phone).one();

        if (user == null) {
            // 用户不存在，创建新用户并保存
            user = createUserWithPhone(phone);
        }

        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);

        // 保存用户到session中
        session.setAttribute("SESSION_USER_KEY",userDTO);

        return null;
    }

    private User createUserWithPhone(String phone) {
        User user = new User();
        user.setPhone(phone);
        String nickname = RandomUtil.randomString(8);
        user.setNickName( USER_NICK_NAME_PREFIX + nickname);
        save(user);
        return user;
    }
}
